package com.gzw.dms.activity;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.gzw.dms.BuildConfig;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.BaseSpinnerAdapter;
import com.gzw.dms.bean.ShippingOrderInfo;
import com.gzw.dms.bean.SingnInfo;
import com.gzw.dms.bean.SpinnerInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.DateUtil;
import com.gzw.dms.utils.FileUtil;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.L;
import com.gzw.dms.utils.ScreenUtils;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.ToolFor9Ge;
import com.gzw.dms.utils.UrlUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StorageUtils;


public class  ScanActivity extends BaseActivity {
    private Button btn_sign;
    private String ddid;
    private EditText et_actual_number;
    private EditText et_copies_number, et_sign_user;
    private EditText et_defect_number;
    private EditText et_sign_remarks;
    private EditText et_sign_name;
    private EditText et_sign_usernumber;
    private EditText et_sign_number;
    private int imgH = 800;
    private int imgW = 600;
    private ImageView iv_uploading,iv_uploading1,iv_uploading2,iv_uploading3;
    private Context mContext;
    private String newFileName;
    private String isUploadPhotos = "0";
    private  String fileRoot = "signorderImages";
    private Spinner sp_sign_result;
    private TextView tv_sign_time, tv_shiping_order_num1, tv_shiping_order_num2, tv_shipping_order_state1,
            tv_shipping_order_state2, tv_send_mechanism1, tv_send_mechanism2, tv_send_time1, tv_send_time2,
            tv_end_address1, tv_end_address2, tv_receipt_tel,
            tv_copies_number, tv_goods_name1, tv_goods_name2, tv_trade_agency1, tv_trade_agency2,
            tv_goods_num1, tv_goods_num2, tv_goods_weight1, tv_goods_weight2, tv_goods_vol1, tv_goods_vol2,
            tv_sign_user1, tv_sign_usernumber, tv_sign_name, tv_actual_number,tv_receipt_tel2,
            tv_defect_number,tv_sign_number,tv_shiping_order_goid1,tv_shiping_order_goid2,ic_remarks1,ic_remarks2;
    private Intent mIntent;
    private ShippingOrderInfo shippingOrder;
    private SingnInfo info;
    private ProgressDialog mProgressDialog;
    private Toolbar toolbar;
    private java.lang.String tag="ScanActivity---->";
    private String path;
    private int REQUEST_CODE_CAMERA=1;

    private String fileName1,fileName2,fileName3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);
        source();
        initConfig();
        init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_scan1);
    }

    @Override
    public void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        btn_sign = ((Button) findViewById(R.id.btn_sign));
//        iv_uploading = ((ImageView) findViewById(R.id.iv_uploading));
//        tv_sign_time = ((TextView) findViewById(R.id.tv_sign_time));
        et_sign_remarks = ((EditText) findViewById(R.id.et_sign_remarks));
        sp_sign_result = ((Spinner) findViewById(R.id.sp_sign_result));
        iv_uploading1 = ((ImageView) findViewById(R.id.iv_uploading1));
        iv_uploading2 = ((ImageView) findViewById(R.id.iv_uploading2));
        iv_uploading3 = ((ImageView) findViewById(R.id.iv_uploading3));
        iv_uploading2.setVisibility(View.GONE);
        iv_uploading3.setVisibility(View.GONE);
        tv_shiping_order_goid1 = (TextView) findViewById(R.id.ic_shiping_order_goid).findViewById(R.id.tv_left);
        tv_shiping_order_goid2 = (TextView) findViewById(R.id.ic_shiping_order_goid).findViewById(R.id.tv_right);
        tv_shiping_order_num1 = (TextView) findViewById(R.id.ic_shiping_order_num).findViewById(R.id.tv_left);
        tv_shiping_order_num2 = (TextView) findViewById(R.id.ic_shiping_order_num).findViewById(R.id.tv_right);
        tv_shipping_order_state1 = (TextView) findViewById(R.id.ic_shipping_order_state).findViewById(R.id.tv_left);
        tv_shipping_order_state2 = (TextView) findViewById(R.id.ic_shipping_order_state).findViewById(R.id.tv_right);
        tv_send_mechanism1 = (TextView) findViewById(R.id.ic_send_mechanism).findViewById(R.id.tv_left);
        tv_send_mechanism2 = (TextView) findViewById(R.id.ic_send_mechanism).findViewById(R.id.tv_right);
        tv_send_time1 = (TextView) findViewById(R.id.ic_send_time).findViewById(R.id.tv_left);
        tv_send_time2 = (TextView) findViewById(R.id.ic_send_time).findViewById(R.id.tv_right);
        tv_end_address1 = (TextView) findViewById(R.id.ic_end_address).findViewById(R.id.tv_left);
        tv_end_address2 = (TextView) findViewById(R.id.ic_end_address).findViewById(R.id.tv_right);
        tv_goods_name1 = (TextView) findViewById(R.id.ic_goods_name).findViewById(R.id.tv_left);
        tv_goods_name2 = (TextView) findViewById(R.id.ic_goods_name).findViewById(R.id.tv_right);
        tv_trade_agency1 = (TextView) findViewById(R.id.ic_trade_agency).findViewById(R.id.tv_left);
        tv_trade_agency2 = (TextView) findViewById(R.id.ic_trade_agency).findViewById(R.id.tv_right);
        tv_goods_num1 = (TextView) findViewById(R.id.ic_goods_num).findViewById(R.id.tv_left);
        tv_goods_num2 = (TextView) findViewById(R.id.ic_goods_num).findViewById(R.id.tv_right);
        tv_goods_weight1 = (TextView) findViewById(R.id.ic_goods_weight).findViewById(R.id.tv_left);
        tv_goods_weight2 = (TextView) findViewById(R.id.ic_goods_weight).findViewById(R.id.tv_right);
        tv_goods_vol1 = (TextView) findViewById(R.id.ic_goods_vol).findViewById(R.id.tv_left);
        tv_goods_vol2 = (TextView) findViewById(R.id.ic_goods_vol).findViewById(R.id.tv_right);
        tv_sign_user1 = (TextView) findViewById(R.id.ic_sign_user).findViewById(R.id.tv_left);
        tv_receipt_tel = (TextView) findViewById(R.id.ic_receipt_tel).findViewById(R.id.tv_left);
        tv_copies_number = (TextView) findViewById(R.id.ic_copies_number).findViewById(R.id.tv_left);
        tv_sign_usernumber = (TextView) findViewById(R.id.ic_sign_usernumber).findViewById(R.id.tv_left);
        tv_sign_name = (TextView) findViewById(R.id.ic_sign_name).findViewById(R.id.tv_left);
        tv_sign_number=(TextView) findViewById(R.id.ic_sign_number).findViewById(R.id.tv_left);
        tv_receipt_tel2 = (TextView) findViewById(R.id.ic_receipt_tel).findViewById(R.id.tv_right);
        et_copies_number = (EditText) findViewById(R.id.ic_copies_number).findViewById(R.id.et_right);
        et_sign_name = (EditText) findViewById(R.id.ic_sign_name).findViewById(R.id.et_right);
        et_sign_usernumber = (EditText) findViewById(R.id.ic_sign_usernumber).findViewById(R.id.et_right);
//        et_sign_username = (EditText) findViewById(R.id.ic_sign_username).findViewById(R.id.et_right);
        et_sign_user = (EditText) findViewById(R.id.ic_sign_user).findViewById(R.id.et_right);
        et_sign_number = (EditText) findViewById(R.id.ic_sign_number).findViewById(R.id.et_right);
        ic_remarks1 = (TextView) findViewById(R.id.ic_remarks).findViewById(R.id.tv_left);
        ic_remarks2 = (TextView) findViewById(R.id.ic_remarks).findViewById(R.id.tv_right);

    }

    @Override
    protected void initData() {
        fileName1="";
        fileName2="";
        fileName3="";
        mContext = this;
        toolbar.setTitle("运单签收");
        setSupportActionBar(toolbar);
        ArrayList ls = new ArrayList();
        ls.add(new SpinnerInfo("1", "正常签收"));
        ls.add(new SpinnerInfo("0", "异常签收"));

        tv_shiping_order_num1.setText("货运编号:");
        tv_shiping_order_goid1.setText("出货订单号:");
        tv_shipping_order_state1.setText("运单状态:");
        tv_send_mechanism1.setText("受理机构:");
        tv_send_time1.setText("起运时间:");
        tv_end_address1.setText("收货客户地址:");
        tv_goods_name1.setText("货物名称:");
        tv_trade_agency1.setText("代收货款:");
        tv_goods_num1.setText("总件数:");
        tv_goods_weight1.setText("总重量:");
        tv_goods_vol1.setText("总体积:");
        tv_sign_user1.setText("*收货联系人:");
        tv_receipt_tel.setText("收货客户电话:");
        tv_copies_number.setText("*回单份数:");
        tv_sign_usernumber.setText("*收货人证件号:");
        tv_sign_name.setText("收货代理人:");
        tv_sign_number.setText("收货代理人证件号:");
        ic_remarks1.setText("发货备注:");

//        tv_sign_name.setTextColor(getResources().getColor(R.color.black));
//        tv_sign_number.setTextColor(getResources().getColor(R.color.black));
//        tv_sign_username.setTextColor(getResources().getColor(R.color.black));


        BaseSpinnerAdapter Adapter = new BaseSpinnerAdapter(mContext, ls);
        sp_sign_result.setAdapter(Adapter);
        mIntent = getIntent();
        shippingOrder = (ShippingOrderInfo) mIntent.getExtras().get(
                "shippingOrder");

        et_copies_number.setInputType(InputType.TYPE_CLASS_NUMBER);
        et_sign_usernumber.setInputType(InputType.TYPE_CLASS_NUMBER);
        et_sign_number.setInputType(InputType.TYPE_CLASS_NUMBER);
        et_sign_remarks.requestFocus();
        isCameraCanUse();
    }

    @Override
    public void initEvents() {
        btn_sign.setOnClickListener(new myOnClick());
        iv_uploading1.setOnClickListener(new myOnClick());
        iv_uploading2.setOnClickListener(new myOnClick());
        iv_uploading3.setOnClickListener(new myOnClick());
        toolbar.setNavigationOnClickListener(new myOnClick());
        sp_sign_result.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                SpinnerInfo spinnerInfo = (SpinnerInfo) sp_sign_result.getSelectedItem();

                String type = spinnerInfo.getId();
                if (type.equals("0")) {
                    et_sign_remarks.setHint("必填");

                } else if (type.equals("1")) {

                    et_sign_remarks.setHint("非必填");

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
    }

    public void source() {
        iv_uploading1.getLayoutParams().height = (ScreenUtils
                .getScreenWidth(mContext) / 3);
        iv_uploading1.getLayoutParams().width = (ScreenUtils
                .getScreenWidth(mContext) / 3);
        iv_uploading2.getLayoutParams().height = (ScreenUtils
                .getScreenWidth(mContext) / 3);
        iv_uploading2.getLayoutParams().width = (ScreenUtils
                .getScreenWidth(mContext) / 3);
        iv_uploading3.getLayoutParams().height = (ScreenUtils
                .getScreenWidth(mContext) / 3);
        iv_uploading3.getLayoutParams().width = (ScreenUtils
                .getScreenWidth(mContext) / 3);

//        tv_receipt_tel2.setText(shippingOrder.getReceipt_tel());
        et_copies_number.setText(shippingOrder.getCopies_number());
        et_sign_user.setText(shippingOrder.getReceipt_name());

        tv_shiping_order_num2.setText(shippingOrder.getShiping_order_num());
        tv_shiping_order_goid2.setText(shippingOrder.getShiping_order_goid());

        Integer state = shippingOrder.getShipping_order_state();
        if (state == 0) {
            tv_shipping_order_state2.setText("未出库");
        } else if (state == 1) {
            tv_shipping_order_state2.setText("分配运单");
        } else if (state == 2) {
            tv_shipping_order_state2.setText("司机接单");
        } else if (state == 3) {
            tv_shipping_order_state2.setText("电子围栏签收");
        }else if (state == 4) {
            tv_shipping_order_state2.setText("实际签收");
        }
        tv_send_mechanism2.setText(shippingOrder.getSend_mechanism());
        tv_send_time2.setText(shippingOrder.getSend_time());
        tv_end_address2.setText(shippingOrder.getEnd_mechanism());
        tv_goods_name2.setText(shippingOrder.getGoods_name());
        tv_trade_agency2.setText(shippingOrder.getTrade_agency());
        tv_goods_num2.setText(String.valueOf(shippingOrder.getGoods_num()));
        tv_goods_weight2.setText(shippingOrder.getGoods_weight());
        tv_goods_vol2.setText(shippingOrder.getGoods_vol());
        ddid = shippingOrder.getShiping_order_id();
        et_copies_number.setText(shippingOrder.getIs_recept());
        et_sign_usernumber.setText(shippingOrder.getReceipt_tel());
        ic_remarks2.setText(shippingOrder.getRemarks());
        tv_receipt_tel2.setText(shippingOrder.getReceipt_tel());

    }



    /**
     * 检验是否有SD卡
     * @true or false
     */
    public static boolean isHaveSDCard() {
        Boolean isExist = Environment
                .getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        return isExist;
    }

    public void SaveHttpClientPost() {
        if (isNull(et_sign_usernumber)) {
            T.showShort(mContext, "收货人证件号不能为空");
            return;
        }

        if (isNull(et_copies_number)) {
            T.showShort(mContext, "回单份数不能为空");
            return;
        }

        isUploadPhotos = FileUtil.getInstance().isUpload();
        if (isUploadPhotos=="0") {
            T.showShort(mContext, "请上传图片");
            return;
        }else if(isUploadPhotos=="1"){
            T.showShort(mContext, "请等待图片上传");
            return;
        }

        if (info == null)
            info = new SingnInfo();
        info.setOrder_id(ddid);
        info.setOrder_number(tv_shiping_order_num2.getText().toString().trim());
        info.setSign_user(et_sign_user.getText().toString().trim());
//        info.setSign_userphone(tv_receipt_tel2.getText().toString().trim());
        info.setSign_usernumber(et_sign_usernumber.getText().toString().trim());
        SpinnerInfo spinnerInfo=(SpinnerInfo)sp_sign_result.getSelectedItem();
        int result = Integer.valueOf(spinnerInfo.getId());
        info.setSign_result(result);
        info.setCopies_number(et_copies_number.getText()
                .toString());

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String date=sdf.format(new java.util.Date());
        info.setSign_time(date);
        if (result==0){
            if (isNull(et_sign_remarks)) {
                T.showShort(mContext, "备注不能为空");
                return;
            }
        }
        info.setSign_remarks(et_sign_remarks.getText().toString().trim());
        info.setSign_usernumber(et_sign_usernumber.getText().toString().trim());
        info.setSign_name(et_sign_name.getText().toString().trim());
        info.setSign_number(et_sign_number.getText().toString().trim());
        info.setLat(MyApplication.getLat());
        info.setLng(MyApplication.getLng());
        SignShipOrder signShipOrder = new SignShipOrder();
        signShipOrder.execute(info);

    }

    public class SignShipOrder extends AsyncTask<SingnInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在签收中...");
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);

        }

        protected String doInBackground(SingnInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            String str = fileName1+","+fileName2+","+fileName3;
            map.put("singnInfo", params[0]);
            map.put("newFileName", str);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appSignShipOrder"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    FileUtil.getInstance().noUpload();
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sign:
                    SaveHttpClientPost();
                    break;

                case R.id.iv_uploading1:

                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            path = resultList.get(0).getPhotoPath().toString();
                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .showImageOnFail(R.drawable.ic_gf_default_photo)
                                    .showImageForEmptyUri(R.drawable.ic_gf_default_photo)
                                    .showImageOnLoading(R.drawable.ic_gf_default_photo).build();
                            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file:/" + path, iv_uploading1, options);
                            iv_uploading2.setVisibility(View.VISIBLE);

                            if (!isNull(path)) {
                                fileName1 = shippingOrder.getShiping_order_num().trim()+ "--" +DateUtil.getFileName() ;
                                uploadPhotos(path, fileName1);

                            }
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            T.showShort(getApplicationContext(), errorMsg);
                            Log.e("onHanlderFailure", "");
                        }
                    });
                    break;
                case R.id.iv_uploading2:
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            path = resultList.get(0).getPhotoPath().toString();
                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .showImageOnFail(R.drawable.ic_gf_default_photo)
                                    .showImageForEmptyUri(R.drawable.ic_gf_default_photo)
                                    .showImageOnLoading(R.drawable.ic_gf_default_photo).build();
                            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file:/" + path, iv_uploading2, options);
                            iv_uploading3.setVisibility(View.VISIBLE);

                            if (!isNull(path)) {
                                fileName2 = shippingOrder.getShiping_order_num().trim()+ "--" +DateUtil.getFileName();
                                uploadPhotos(path, fileName2);

                            }
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            T.showShort(getApplicationContext(), errorMsg);
                            Log.e("onHanlderFailure", "");
                        }
                    });

                    break;
                case R.id.iv_uploading3:
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            path = resultList.get(0).getPhotoPath().toString();
                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .showImageOnFail(R.drawable.ic_gf_default_photo)
                                    .showImageForEmptyUri(R.drawable.ic_gf_default_photo)
                                    .showImageOnLoading(R.drawable.ic_gf_default_photo).build();
                            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file:/" + path, iv_uploading3, options);
                            if (!isNull(path)) {
                                fileName3 = shippingOrder.getShiping_order_num().trim()+ "--" +DateUtil.getFileName();
                                uploadPhotos(path, fileName3);

                            }
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            T.showShort(getApplicationContext(), errorMsg);
                            Log.e("onHanlderFailure", "");
                        }
                    });
                    break;
                default:
                    finish();
                    break;
            }
        }
    }


    private void uploadPhotos(String path, String fileName){

                   Bitmap bitmap = null;
                   File file = new File(path);
                    if (file.exists()) {
                        try {
                            FileInputStream fis = new FileInputStream(file);
                            bitmap = BitmapFactory.decodeStream(fis);
                            fis.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (bitmap!=null) {
                            bitmap = ToolFor9Ge.zoomImg(bitmap, imgW, imgH);
                            FileUtil.getInstance().uploadFile(bitmap, fileName,fileRoot);
                        }

                        if(bitmap.isRecycled()==false) //如果没有回收
                            bitmap.recycle();
                    }
    }

    private void initConfig() {
        //配置主题
        //ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder()

                .build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(false)
                .build();

        //配置imageloader
        ImageLoader imageloader = new UILImageLoader();
        //设置核心配置信息
        CoreConfig coreConfig = new CoreConfig.Builder(getApplicationContext(), imageloader, theme)
                .setDebug(BuildConfig.DEBUG)
                .setFunctionConfig(functionConfig)

                .build();
        GalleryFinal.init(coreConfig);
    }

    private void init() {
        File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3) // default
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(tag, "onStart called.");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(tag, "onRestart called.");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(tag, "onResume called.");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(tag, "onPause called.");
    }

    @Override
    protected void onStop() {
        L.i(tag, "onStop()");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        L.i(tag, "onDestroy()");
        Intent sevice = new Intent(this, ScanActivity.class);
        this.startService(sevice);
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("filePath", path);
//        Log.d(TAG, "onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (TextUtils.isEmpty(path)) {
            path = savedInstanceState.getString("filePath");
        }
    }
    public  boolean isCameraCanUse() {
        boolean canUse = true;
        Camera mCamera = null;
        try {
            // TODO camera驱动挂掉,处理??
            mCamera = Camera.open();
        } catch (Exception e) {
            canUse = false;
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("摄像头权限未开启，请开启权限。");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.show();
        }
        if (canUse) {
            mCamera.release();
            mCamera = null;
        }

        return canUse;
    }
}